package com.oocl.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.oocl.dao.WareHouseDao;
import com.oocl.pojo.User;
import com.oocl.pojo.Warehouse;
import com.oocl.util.DBUtil;

public class WareHouseDaoImpl implements WareHouseDao {

	@Override
	public int addWareHouse(Warehouse c) {
		String sql = "insert into warehouse(id, addr) values (?,?)";
		
		PreparedStatement pst =null;
		Connection con = null;
		int m = 0; 
		
		try {
			con = DBUtil.createConnection();
			pst = con.prepareStatement(sql);
			pst.setInt(1, c.getId());
			pst.setString(2, c.getAddr());
			
			m = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(con, pst, null);
		}
		return m;
	}

	@Override
	public List<Warehouse> loadWareHouse() {
		List<Warehouse> list = new ArrayList<Warehouse>();
		String sql = "select * from warehouse";
		PreparedStatement pst = null;
		ResultSet rs = null;
		Connection con = DBUtil.createConnection();
		Warehouse c = null;
		try {
			pst = con.prepareStatement(sql);
			rs = pst.executeQuery();
			
			while(rs.next()){
				c = new Warehouse();
				c.setId(rs.getInt("id"));
				c.setAddr(rs.getString("addr"));
				list.add(c);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(con, pst, rs);
		}
		return list;
	}

	@Override
	public void initWareHouse() {
		Warehouse ware1 = new Warehouse(1, "BeiJing");
		Warehouse ware2 = new Warehouse(2, "TianJing");
		Warehouse ware3 = new Warehouse(3, "ShangHai");
		addWareHouse(ware1);
		addWareHouse(ware2);
		addWareHouse(ware3);
	}

	@Override
	public int findIdByAddr(String addr) {
		String sql = "select id from warehouse where addr=?";
		PreparedStatement pst = null;
		ResultSet rs = null;
		int id = -1;
		Connection con = DBUtil.createConnection();
		Warehouse c = null;
		try {
			pst = con.prepareStatement(sql);
			pst.setString(1, addr);
			rs = pst.executeQuery();
			
			if(rs.next()){
				id = rs.getInt("id");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(con, pst, rs);
		}
		return id;
	}
	
	public static void main(String[] args) {
		WareHouseDaoImpl impl = new WareHouseDaoImpl();
		impl.initWareHouse();
	}
}
